module uart_tx (
    input clk,
    input rst_n,
    input [7:0] din,
    input din_vld,
    output reg dout
);
    parameter BAUD = 434;

    reg [8:0] cnt_bsp;
    wire add_cnt_bsp;
    wire end_cnt_bsp;

    reg [3:0] cnt_bit;
    wire add_cnt_bit;
    wire end_cnt_bit;

    reg flag;		
    reg [8:0] data;

    always @(posedge clk or negedge rst_n) begin
        if(!rst_n) cnt_bsp <= 0;
        else if(add_cnt_bsp)
            if(end_cnt_bsp) cnt_bsp <= 0;
            else cnt_bsp <= cnt_bsp + 1;
        else cnt_bsp <= cnt_bsp;
    end
    assign add_cnt_bsp = flag;
    assign end_cnt_bsp = add_cnt_bsp && (cnt_bsp == BAUD - 1);


    always @(posedge clk or negedge rst_n) begin
        if(!rst_n) cnt_bit <= 0;
        else if(add_cnt_bit)
            if(end_cnt_bit) cnt_bit <= 0;
            else cnt_bit <= cnt_bit + 1;
        else cnt_bit <= cnt_bit;
    end
    assign add_cnt_bit = end_cnt_bsp;
    assign end_cnt_bit = add_cnt_bit && (cnt_bit == 8);

    always @(posedge clk or negedge rst_n)begin
        if(!rst_n) flag = 0;
        else if (din_vld) flag <=1;
        else if (end_cnt_bit) flag <=0;
        else flag <= flag;
    end

    always @(posedge clk or negedge rst_n)begin
        if(!rst_n) data <= !0;
        else if (din_vld)  data <= {din,1'b0} ; // 数据加上起始位
        else data <= data;
    end

    always @(posedge clk or negedge rst_n)begin
        if(!rst_n) dout <=1;
        else if (cnt_bsp == 1) dout <= data[cnt_bit]; // 串行输出 LSB
        else if (end_cnt_bit) dout <= 1'b1;
        else dout <= dout;  
    end


endmodule
